<template >
  <div class="last-sync-class" v-if="false">
    <div v-if="notWidget&&viewList.length>0"
      style="height:32px;text-align:left;border-top: 1px solid #eee;font-size:14px;display: flex;justify-content: space-between;align-items: center;">
      <div v-for="(item,index) in viewList" :key="index" style="font-size:14px;margin-left:16px">
          <div :style="{'cursor': $route.path.includes('/publicReport')?'':'pointer'}">
          <el-tooltip placement="bottom" :open-delay="1000" :disabled="$route.path.includes('/publicReport') || $route.path.includes('/publicReportPdf')">
          <div slot="content" v-loading="syncLoading" element-loading-background="rgba(0, 0, 0, 0.8)">
            <span v-on:click="goToUrl(item.datasetId)"
              style="text-decoration:underline;cursor: pointer;">{{item.name}}</span>
            <i class="cuifont icon_arrow_generate" style="cursor: pointer;text-align:right;margin-left:10px;"
              @click.stop="manuallySync(item,index)"></i>
            <br />
            {{'Last Synched : '+timeformat(item.refreshTime)}}
            <br />
            {{'Sync Frequency : '+ item.maxSyncFrequency}}
          </div>
          <i class="el-icon-time" style="margin-right:8px;" v-if="item.refreshTime"></i>
        </el-tooltip>
        <span v-if="item.refreshTime&&domShow" ref="LastSyncTimeNode">{{formatLastSyncTime(item.refreshTime)}}</span>
        </div>
       
      </div>
      <slot></slot>
    </div>
    <div v-else
      style="height:32px;text-align:left;border-top: 1px solid #eee;font-size:14px;display: flex;justify-content: flex-end;align-items: center;">
      <slot></slot>    
      <!-- <i class="el-icon-time" style="margin-left:16px;margin-right:8px;"></i>
        <span> {{lastUpdateTime}} </span> -->
      <!-- {{formatErrorStatus(errorStatus)}} -->
    </div>
  </div>
</template>
<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import moment from 'moment'
import { GlobalTimeformat } from '@/utils/common'
export default {
  mixins: [mixinGadgetViewModule],

  props: {
    currentTime: {
      type: Date,
      default: function () {
        return null
      }
    },
    linkedDatasetList: {
      type: Array,
      default: () => { return [] }
    },
    errorStatus: {
      type: String,
      default: function () {
        return ''
      }
    }
  },
  watch: {
    currentTime (val) {
      this.lastUpdateTimer(val)
    }
  },
  data () {
    return {
      notWidget: !window.location.pathname.includes('Widgets'),
      lastUpdateTime: null,
      timers: null,
      syncTimers: null,
      syncLoading: false,
      domShow:true
    }
  },
  computed: {
   
    viewList () {
      let temp = []
      if(this.linkedDatasetList&&Array.isArray(this.linkedDatasetList)&&this.linkedDatasetList.length>0){
          for (let index = 0; index < this.linkedDatasetList.length; index++) {
          const element = this.linkedDatasetList[index]
          if (element.refreshTime) {
            temp.push(element)
          }
        }
      }
      return temp
    }
  },
  mounted () {
    let Node = this.$refs.LastSyncTimeNode
    if (Node && Node[0].offsetHeight < Node[0].getBoundingClientRect().height) {
      this.domShow = false
    } else {
      this.domShow = true
    }
  },
  created () {
    this.lastUpdateTimer(this.currentTime)
  },
  beforeDestroy () {
    clearInterval(this.timers)
    clearInterval(this.syncTimers)
  },
  methods: {
    lastUpdateTimer (time) {
      this.lastUpdateTime = moment(time).fromNow()
      clearInterval(this.timers)
      this.timers = setInterval(() => {
        this.lastUpdateTime = moment(time).fromNow()
      }, 1000)
    },
    formatLastSyncTime (time) {
      let tempTime = null
      tempTime = time
      let nowTime = moment(moment.tz(tempTime, this.$store.state.user.timezoneId).format()).fromNow()
      return nowTime
    },
    timeformat (time) {
      return GlobalTimeformat(time, 'HH:mm')
    },
    goToUrl (data) {
      this.$router.push({ path: `dataset-${data}`, query: { pageid: `${data}` } })
    },
    manuallySync (data, index) {
      this.syncLoading = true
      const params = {
        // tenantCode: this.$store.state.user.tenantCode
      }
      if (data.datasetId && data.datasetLayerId) {
        params.id = data.datasetLayerId
        params.type = 'datasetLayer'
      } else {
        params.id = data.datasetId
        params.type = 'dataset'
      }
      params.tenantCode = this.$store.state.user.tenantCode
      this.$interface.apiManager.getSyncStartApi(params).then(({ data: res }) => {
        this.syncLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data && res.data.length > 0) {
          this.syncResult(params, res.data, data, index)
        }
      }).catch(() => { this.syncLoading = false })
    },
    syncResult (data, resultList, viewData, itemIndex) {
      const params = {
        ...data
      }
      this.$interface.apiManager.getSyncResultApi(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        let successNum = 0
        if (res.data && res.data.length > 0) {
          for (let index = 0; index < resultList.length; index++) {
            const elementResult = resultList[index]
            for (let i = 0; i < res.data.length; i++) {
              const element = res.data[i]
              if (elementResult.data && element.data && elementResult.data.action === element.data.action) {
                clearInterval(this.syncTimers)
                if (moment(elementResult.data.time).isBefore(element.data.time)) {
                  if (element.data.status === 'OK') {
                    successNum++
                    const temp = {
                      ...viewData
                    }
                    temp.refreshTime = element.data.time
                    this.linkedDatasetList.splice(itemIndex, 1, temp)
                    this.$forceUpdate()
                    this.$emit('updateQuery')
                  }
                } else {
                  this.syncStart(data, resultList, viewData, itemIndex)
                }
              }
            }
          }
          if (successNum === resultList.length) {
            this.syncLoading = false
            clearInterval(this.syncTimers)
            return this.$message.success('Sync Success')
          }
        } else {
          this.syncStart(data, resultList, viewData, itemIndex)
        }
      }).catch(() => {
        this.syncLoading = false
      })
    },
    syncStart (data, resultList, viewData, itemIndex) {
      clearInterval(this.syncTimers)
      this.syncTimers = setInterval(() => {
        this.syncResult(data, resultList, viewData, itemIndex)
      }, 5000)
    },
    formatErrorStatus (item) {
      let temp = ''
      switch (item) {
        case '504':
          temp = 'error 504: Request timed out.'
          break

        default:
          break
      }
      return temp
    }

  }
}
</script>
<style  lang='scss'>
.popoverBackB {
  background: #303133 !important;
  color: #fff !important;
}

.last-sync-class {
  background-color: #fff;
}
</style>
